package com.jinly.ryder.common.web;

import com.jinly.ryder.common.service.model.BaseEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class EnumsController implements InitializingBean {

    private Map<String, BaseEnum[]> baseEnumMap = new HashMap<>();

    @GetMapping("enums/{name}")
    public BaseEnum[] enums(@PathVariable String name) {
        return baseEnumMap.get(name);

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources = resolver.getResources("classpath*:com/jinly/ryder/*/service/model/*.class");
        for (Resource r : resources) {
            MetadataReader reader = metaReader.getMetadataReader(r);
            Class clazz = Class.forName(reader.getClassMetadata().getClassName());
            if (clazz.isEnum() && BaseEnum.class.isAssignableFrom(clazz) && clazz != BaseEnum.class) {
                Object[] enums = clazz.getEnumConstants();
                baseEnumMap.put(clazz.getSimpleName(), (BaseEnum[]) enums);
            }
        }
    }
}
